/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.security.utils;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

import com.iiifi.kite.core.exception.ServiceException;
import com.iiifi.kite.core.model.KiteAccount;
import com.iiifi.kite.core.spring.SpringContextUtils;
import com.iiifi.kite.configuration.KiteProperties;
import com.iiifi.kite.security.enums.KiteSecurityCode;
import com.iiifi.kite.security.service.KiteSecurityService;

import lombok.extern.slf4j.Slf4j;

/**
 * KiteAccountUtils
 *
 * @author kite@iiifi.com 花朝
 */
@Slf4j
public class KiteAccountUtils {
    private KiteAccountUtils() {}

    /**
     * 获取当前用户
     *
     * @return {KiteAccount}
     */
    public static KiteAccount getAccount() {
        KiteAccount account = null;
        HttpServletRequest request = KiteUtils.getRequest();
        KiteProperties kiteProperties = SpringContextUtils.getBean(KiteProperties.class);
        KiteSecurityService kiteAccountService = SpringContextUtils.getBean(KiteSecurityService.class);
        if (request != null) {
            account = (KiteAccount) request.getAttribute(KiteUtils.ACCOUNT_ATTRIBUTES_ATTRIBUTE);
        }
        if (account != null) {
            return account;
        } else {
            if (request == null || kiteProperties == null) {
                return null;
            }
            String token = KiteUtils.getToken(request, kiteProperties);
            String deviceId = KiteUtils.getDeviceId(request, kiteProperties);
            if (!StringUtils.hasText(token)) {
                log.warn("kite-security 查询账号信息失败 ==> token is null");
                throw new ServiceException(KiteSecurityCode.TOKEN_IS_INVALID);
            }
            // 查询账号信息
            if (kiteAccountService == null) {
                log.warn("kite-security 查询账号信息失败 ==> kiteAuthService is null");
                return null;
            }
            return kiteAccountService.getAccount(token, deviceId);
        }
    }
}
